package com.jack.collection;

import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by zhang_j on 2019/11/28
 * Comparable&Comparator都是用来实现集合中元素的比较、排序的
 *      Comparable是在集合内部定义的方法实现的排序，Comparator是在集合外部实现的排序
 *      自定义的类实现Comparable接口就可以以实现的顺序进行排序
 */
public class ComparableAndComparator {

    public static void main(String[] args) {
        new ComparableAndComparator().comparatorTest();
    }
    public void comparatorTest(){
        List<Student> list = Lists.newArrayList();
        list.add(new Student("jack",12));
        list.add(new Student("tom",14));
        list.add(new Student("mary",8));
        list.add(new Student("shark",22));
        Collections.sort(list);

        System.out.println(list.toString());

        list.sort(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getAge()-o2.getAge();
            }
        });
        System.out.println(list.toString());
//        list.sort((a,b)->a-b);

    }

    public class Student implements Comparable<Student>{

        String name;
        int age;

        @Override
        public int compareTo(Student s) {
            return this.getAge() - s.getAge();
        }

        Student(String name,int age){
            this.name = name;
            this.age = age;
        }

        public int getAge() {
            return this.age;
        }

        @Override
        public String toString() {
            return "Name:"+name +","
                    +"Age:"+age+";";
        }
    }
}
